import React, { Component, PureComponent } from "react";
import PropTypes from "prop-types";
import "./index.less";
import { removeNullProp } from "../../tool/objectUtil";

export default class Popup extends PureComponent {
  mask = null;

  constructor(props) {
    super(props);
    this.state = { show: false };
    this.handleContentTransitonEnd = this.handleContentTransitonEnd.bind(this);
    this.handleClickMask = this.handleClickMask.bind(this);
  }

  /**
   * 这个函数在父组件re-render，或者自身props和state改变都会触发
   */
  static getDerivedStateFromProps(nextProps, prevState) {
    const { show } = nextProps;
    if (typeof show === "boolean" && show !== prevState.show) {
      return { show: show };
    }
    return null;
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.show !== this.state.show && this.state.show === true) {
      this.mask.style.display = "block";
    }
  }

  show() {
    this.setState({ show: true });
  }

  hide(e) {
    this.setState({ show: false });
  }

  //  popup内容滑动动画结束后
  handleContentTransitonEnd() {
    let { show } = this.state;
    if (!show) this.mask.style.display = show ? "block" : "none";
  }

  // 点击背景
  handleClickMask() {
    const { clickMask } = this.props;
    if (clickMask) clickMask();
    else this.hide(e);
  }

  render() {
    let { show } = this.state;
    let { direction, width, height, children, containerClass, contentClass } =
      this.props;
    let cntentStyle = { width, height };
    removeNullProp(cntentStyle);
    direction = direction || "right";
    return (
      <div className={`b-popup ${containerClass || ""}`}>
        <div
          className="b-popup-mask"
          ref={(mask) => {
            this.mask = mask;
          }}
          onClick={this.handleClickMask}
          style={{ display: "none" }}
        ></div>
        <div
          className={`b-popup-content ${
            contentClass || ""
          } slide-${direction} ${show ? `slide-${direction}--show` : ""}`}
          onTransitionEnd={this.handleContentTransitonEnd}
          style={cntentStyle}
        >
          {children}
        </div>
      </div>
    );
  }
}

Popup.propTypes = {
  show: PropTypes.bool,
  clickMask: PropTypes.func,
  direction: PropTypes.string,
  width: PropTypes.string,
  height: PropTypes.string,
  containerClass: PropTypes.string,
  contentClass: PropTypes.string,
};
